<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Phone book</title>
</head>
<body>
    <h2>Enter Contacts </h2>
        <label for="username">Name:</label><br>
        <input type="text" id="username" name="username"><br>
        <label for="age">Address:</label><br>
        <input type="text" id="address" name="address"><br>
        <label for="tel">tel:</label><br>
        <input type="text" id="tel" name="tel"><br><br>
        
        <button id="add">添加</button>
        <button id="change">修改</button>
        <button id="delete">删除</button>
        <button id="refresh">更新</button>
    
<table border="1">
    <thead>
      <tr>
        <td>id</td>
        <td>用户名</td>
        <td>住址</td>
        <td>电话</td>
      </tr>
     
    </thead>
    
    <tbody>
         <tr>
        <td>1</td>
        <td>用户名</td>
        <td>住址</td>
        <td>电话</td>
      </tr>
      <tr>
        <td>2</td>
        <td>用户名</td>
        <td>住址</td>
        <td>电话</td>
      </tr>
    </tbody>
    </table>
    <script>
        // 通过标识符eventMessage触发不同的事件
        // 0拿到数据
        // 1增加数据
        // 2修改数据
        // 3删除数据
        let eventMessage = 0
        let index = null
        let data = null//表格数据
      let id =null

        // 高亮
        function highlight(){
              const rows = document.querySelectorAll('tbody tr');
          // 为每个 <tr> 元素添加点击事件监听器
        rows.forEach(row => {
            // 获取index
             
            // console.log(row);
            row.addEventListener('click', function() {

            const firstCell = this.querySelector('td:first-child');
             index = parseInt(firstCell.textContent);
            console.log(index);
            
                // 去除其他高亮效果
                rows.forEach(row2=>{
                    row2.classList.remove('highlight')
                })
            // 切换高亮效果的样式
            // console.log(row);
            id = data[index-1]._id
            this.classList.toggle('highlight');
                });
            });
        }

        const ws = new WebSocket('ws://localhost:8080');

        ws.onopen = function() {
            console.log('WebSocket connection established');
        };



        ws.onmessage = function(event) {
            // console.log(`Received message: ${event.data}`);
            data = JSON.parse(event.data)
            
            if (eventMessage == 0) {
            tbody(data)
            } else {
                console.log();
            }
        };


        // 获取
        document.getElementById('refresh').addEventListener('click',async ()=>{
            await getData()
            location.href = location.href
        })
        function getData() {
            eventMessage = 0
            console.log('get');   
            ws.send(JSON.stringify({ eventMessage }));
            tbody(data)
              location.href = location.href
        }
       function tbody(data) {
        document.querySelector('tbody').innerHTML = data.map((item,index) => `
               <tr>
                <td>${index+1}</td>  
                <td>${item.username}</td>  
                <td>${item.address}</td>  
                <td>${item.tel}</td>  
                </tr>
            `).join("")

            // 为这些添加高亮
            highlight()
       }

        // 添加
       document.getElementById('add').addEventListener('click',async function(e) {
            eventMessage = 1
           const username = document.getElementById('username').value;
            const address = document.getElementById('address').value;
            const tel = document.getElementById('tel').value;
            // Send data as a JSON object
           await ws.send(JSON.stringify({ eventMessage:1,username, address,tel }));
            getData()
            location.href = location.href
        });

        // 修改
        document.getElementById('change').addEventListener('click',()=>{
           if(id) {
            eventMessage = 2
               const username = document.getElementById('username').value;
            const address = document.getElementById('address').value;
            const tel = document.getElementById('tel').value;
            ws.send(JSON.stringify({id,eventMessage:2,username, address,tel}))
            getData()
            location.href = location.href
           }
        }) 


        // 删除
        document.getElementById('delete').addEventListener('click',()=>{
            if(id) {
            eventMessage = 3
            ws.send(JSON.stringify({id,eventMessage:3}))
            getData()
            location.href = location.href
           }
        })

        ws.onclose = function(event) {
            console.log('WebSocket connection closed');
        };

        ws.onerror = function(error) {
            console.error('WebSocket error:', error);
        };
    </script>

    <style>
        .highlight {
            background-color: aqua;
        }
    </style>
</body>
</html>